﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace SimpleTFTP
{
    internal class DataPacket : BasePacket
    {
        public short BlockNumber { get; set; }

        public byte[] Data { get; set; }

        public DataPacket(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                this.OpCode = (OpCode)Utilities.ReadInt16(ms);
                this.BlockNumber = (short)Utilities.ReadInt16(ms);
                ms.Seek(4, SeekOrigin.Begin);
                ms.Read(this.Data, 0, (int)ms.Length);
            }
        }

        public DataPacket(byte[] data, short blockNo)
        {
            this.OpCode = OpCode.DATA;
            this.BlockNumber = blockNo;
            this.Data = data;
        }

        public override byte[] ToByteArray()
        {
            List<byte> result = new List<byte>();

            result.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)this.OpCode)));
            result.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(BlockNumber)));
            result.AddRange(Data);

            return result.ToArray();
        }
    }
}